#!/bin/bash

echo "######################################################################################################"
node -v
cnpm -v
echo ${branch}
echo ${gulp_task}
echo ${JENKINS_HOME}
echo ${JOB_NAME}
echo ${WORKSPACE}
echo "######################################################################################################"
cd ${WORKSPACE} && cnpm install --save-dev
cd ${WORKSPACE} && ./node_modules/gulp/bin/gulp.js ${gulp_task}

# 发布到服务器
case $gulp_task in
    "build-cms-test")
    	deploy_project=cms
        deploy_profile=test
        ;;
    "build-web-test")
    	deploy_project=web
        deploy_profile=test
        ;;
    "build-cms-prod")
    	deploy_project=cms
        deploy_profile=prod
        ;;
    "build-web-prod")
    	deploy_project=web
        deploy_profile=prod
        ;;
    *)
    	echo "ERROR GULP_TASK"
        exit
    	;;
esac

build_result_path=${WORKSPACE}/dist/build/${deploy_project}/build.result
chmod 755 ${build_result_path}
build_result=`cat ${build_result_path}`
if [ $build_result == "success" ];then
	echo "#################################################### BUILD SUCCESS ####################################################"
else
	echo "#################################################### BUILD FAIL(${build_result}) ####################################################"
    exit
fi

publish_path=/data/web/huayan-frontend/${deploy_project}/

case $deploy_profile in
	"test")
    	ssh -t root@test.intranet.meishuo.ltd "mkdir -p ${publish_path}"
		chmod 755 -R ${WORKSPACE}
		rsync -av --exclude 'static' ${WORKSPACE}/dist/${deploy_project}/*  root@test.intranet.meishuo.ltd:${publish_path}
    	;;
    "prod")
    	for((i=1; i<=2; i++));do
            ssh -t root@frontend${i}.intranet.meishuo.ltd "mkdir -p ${publish_path}"
            chmod 755 -R ${WORKSPACE}
            rsync -av --exclude 'static' ${WORKSPACE}/dist/${deploy_project}/*  root@frontend${i}.intranet.meishuo.ltd:${publish_path}
        done
    	;;
    *)
    	echo "ERROR PROFILE"
        exit
        ;;
esac
